package cn.laowen.basic.service.impl;

import cn.laowen.basic.constants.BaseConstant;
import cn.laowen.basic.dto.LoginDto;
import cn.laowen.basic.dto.RegisterDto;
import cn.laowen.basic.dto.WeChatDto;
import cn.laowen.basic.exception.BusinessException;
import cn.laowen.basic.jwt.JwtUtils;
import cn.laowen.basic.jwt.LoginResult;
import cn.laowen.basic.jwt.RsaUtils;
import cn.laowen.basic.service.ILoginService;
import cn.laowen.basic.util.AjaxResult;
import cn.laowen.basic.util.HttpClientUtils;
import cn.laowen.basic.util.MD5Utils;
import cn.laowen.basic.util.StrUtils;
import cn.laowen.system.domain.Menu;
import cn.laowen.system.mapper.MenuMapper;
import cn.laowen.system.mapper.PermissionMapper;
import cn.laowen.user.domain.Logininfo;
import cn.laowen.user.domain.User;
import cn.laowen.user.domain.Wxuser;
import cn.laowen.user.mapper.LogininfoMapper;
import cn.laowen.user.mapper.UserMapper;
import cn.laowen.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     *  登录
     * @param loginDto
     */
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();//用户名
        String password = loginDto.getPassword();//密码
        Integer type = loginDto.getType();//type：0员工,1用户
        //1.校验(空校验)
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||StringUtils.isEmpty(type)){
            throw new BusinessException("参数异常!!!");
        }
        //2.根据username + type 查询logininfo  要查询username phone email三个字段
        Logininfo logininfo = logininfoMapper.loadByUserNameAndType(username,type);
        //2.1.查询不到，提示用户不存在
        if (logininfo == null){
            throw new BusinessException("用户不存在!!!");
        }
        //2.2 查到了，校验密码是否一致
        String salt = logininfo.getSalt();//获取到之前加密的密码用的盐值
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);//对前端输入的密码加盐加密
        if (!md5Pwd.equals(logininfo.getPassword())){
            //3.密码错误，提示密码错误
            throw new BusinessException("用户名或密码错误!!!");
        }
        //4.登录成功:查询出当前登录人的菜单权限+按钮权限
            return loginSuccessHandler(logininfo);
        /*//4.1 存储redis
        String token = UUID.randomUUID().toString();//token
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        //因为盐值和密码是敏感信息，所以不能返回到前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;*/
    }

    /***
     * 登录成功后的处理:把登录人信息 + 权限,加密封装成JWT串
     * 返回token + logininfo + menus + permissions
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //根据type判断是否为员工
        if (logininfo.getType() == 0){
            //1.菜单权限
            List<Menu> menus = menuMapper.loadMenuByLogininfoId(logininfo.getId());
            //2.按钮权限
            List<String> permissions = permissionMapper.loadPermissionByLogininfoId(logininfo.getId());
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //把登录人信息 + 权限 加密封装成JWT串，返回给前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        //使用私钥将loginResult加密成Jwt串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);

        //返回token + logininfo + menus + permissions
        Map<String, Object> map = new HashMap<>();
        //token为jwt串
        map.put("token",jwtStr);
        //因为盐值和密码是敏感信息，所以不能返回到前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);//登录人信息
        map.put("menus",loginResult.getMenus());//登陆人菜单权限
        map.put("permissions",loginResult.getPermissions());//登陆人按钮权限
        return map;
    }

        /**
         * 微信三方扫码登录接口
         * @param weChatDto
         * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto weChatDto) {
        String code = weChatDto.getCode();
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("code不能为空!!!");
        }
        //1.通过code从微信获取access_token+openid
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL
                .replace("APPID", BaseConstant.WeChatConstants.APPID)//覆盖APPID
                .replace("SECRET", BaseConstant.WeChatConstants.SECRET)//覆盖SECRET
                .replace("CODE", code);//覆盖CODE
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);//发送请求,返回一个JSON格式字符串
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);//JSON格式字符串转为JSON格式对象
        String accessToken = tokenObj.getString("access_token");//获取参数access_token 接口调用凭证
        String openId = tokenObj.getString("openid");//获取参数openid  授权用户唯一标识
        //2.通过openid查询t_wxuser表，判断是否wxuser存在并且user_id不为空
        Wxuser wxuser = wxuserMapper.loadByopenId(openId);//根据openId查询
        //2.1 有，且userId存在，直接免密登录===第二次之后的扫码登录
        if (wxuser !=null && wxuser.getUserId()!=null){
            Logininfo logininfo =logininfoMapper.loadByUserId(wxuser.getUserId());//根据userid查询
            //4.1 存储redis
            /*String token = UUID.randomUUID().toString();//token
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,
                    30,
                    TimeUnit.MINUTES
            );
            //4.2 返回token + logininfo
            //因为盐值和密码是敏感信息，所以不能返回到前端
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);//返回对象到前端*/
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));//返回对象到前端
        }

        //2.2 没有，这里应该让浏览器跳转到绑定页面，让它自己输入账号和密码来完成绑定
        String binderParm = "accessToken=" + accessToken + "&openId="+ openId;//
        return AjaxResult.me().setSuccess(false).setResultObj(binderParm);
    }

    /**
     * 绑定授权接口
     * @param weChatDto
     * @return
     */
    @Override
    public Map<String, Object> binder(WeChatDto weChatDto) {
        String phone = weChatDto.getPhone();
        String password = weChatDto.getPassword();
        if (StringUtils.isEmpty(phone)
                ||StringUtils.isEmpty(password)
        ){
            throw new BusinessException("参数不能为空!!!");
        }
        //1.根据username 查询t_user是否曾今已经存在
        User user = userMapper.loadByPhone(weChatDto.getPhone());
        //1.1 存在 查询出来，等着绑定
        Logininfo logininfo = null;

        if (user!=null){
            logininfo = logininfoMapper.loadByUserId(user.getId());
        } else {
        //1.2 不存在 生成新的t_user + t_logininfo
            user = weChatDto2User(weChatDto);//register对象转user对象
            logininfo = user2Logininfo(user);//user对象转logininfo对象
            logininfoMapper.save(logininfo);//保存到 t_logininfo
            user.setLogininfoId(logininfo.getId());//给 user设置logininfo_id
            userMapper.save(user);//保存到 t_user

        }

        //2.根据token + openid 去微信查询微信的用户基本信息
        String wxuserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN", weChatDto.getAccessToken())
                .replace("OPENID", weChatDto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxuserUrl);//发起请求,返回一个JSON格式字符串
        //3.根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);//把参数 转成 一个对象
        //4.t_wxuser绑定t_user
       wxuser.setUserId(user.getId());
        //5.保存到t_wxuser
        wxuserMapper.save(wxuser);
        //6.直接免密登录
        //4.1 存储redis
        /*String token = UUID.randomUUID().toString();//token
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        //因为盐值和密码是敏感信息，所以不能返回到前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;*/
        return loginSuccessHandler(logininfo);
    }




    /**
     * user对象转logininfo对象
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);//使用工具类同名原则拷贝,把user中logininfo有的属性copy过去
        logininfo.setType(1);//前端用户注册  设置Type为1：
        return logininfo;
    }

    /**
     * WeChatDto对象转user对象
     * @param weChatDto
     * @return
     */
    private User weChatDto2User(WeChatDto weChatDto) {
        User user = new User();
        user.setUsername(weChatDto.getPhone());//设置用户名
        user.setPhone(weChatDto.getPhone());//设置手机号
        String salt = StrUtils.getComplexRandomString(32);//生成一个32位的盐值
        user.setSalt(salt);//设置盐值
        String md5Password = MD5Utils.encrypByMd5(weChatDto.getPassword() + salt);//使用盐值加密密码
        user.setPassword(md5Password);//设置密码为加密后的密码
        return user;
    }

}
